package com.vrv.app.cyberspace.modules.sys.service.impl;

import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.plugins.Page;
import com.baomidou.mybatisplus.service.impl.ServiceImpl;
import com.vrv.app.cyberspace.common.ddio.ApiV2Service;
import com.vrv.app.cyberspace.common.ddio.DDIORunnable;
import com.vrv.app.cyberspace.common.ddio.TemplateMessage;
import com.vrv.app.cyberspace.common.utils.HttpContextUtils;
import com.vrv.app.cyberspace.common.utils.JSONResult;
import com.vrv.app.cyberspace.config.WXBSystemConfig;
import com.vrv.app.cyberspace.modules.sys.entity.*;
import com.vrv.app.cyberspace.modules.sys.mapper.*;
import com.vrv.app.cyberspace.modules.sys.service.ITodayBulletinTableService;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.interceptor.TransactionAspectSupport;

import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

import static com.vrv.app.cyberspace.common.utils.JSONResult.renderError;
import static com.vrv.app.cyberspace.common.utils.JSONResult.renderSuccess;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author sm
 * @since 2017-12-15
 */
@SuppressWarnings("SpringJavaInjectionPointsAutowiringInspection")
@Service
@Transactional
public class TodayBulletinTableServiceImpl extends ServiceImpl<TodayBulletinTableMapper, TodayBulletinTable> implements ITodayBulletinTableService {
    private static final SimpleDateFormat sdf = new SimpleDateFormat("yyyy年MM月dd日");
    private DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm");
    Logger logger = LoggerFactory.getLogger(RiskTableServiceImpl.class);

    @Autowired
    private TodayBulletinTableMapper todayBulletinTableMapper;
    @Autowired
    private TodayInformationTableMapper todayInformationTableMapper;
    @Autowired
    private UserTableMapper userTableMapper;
    @Autowired
    private BaseTableMapper baseTableMapper;
    @Autowired
    private InformationTableMapper informationTableMapper;
    @Autowired
    private RiskTableMapper riskTableMapper;
    @Autowired
    private EventTableMapper eventTableMapper;
    @Autowired
    private BulletinApprovalTableMapper bulletinApprovalTableMapper;
    @Autowired
    private IndustryTableMapper industryTableMapper;
    @Autowired
    private RegionTableMapper regionTableMapper;
    @Autowired
    private RoleTableMapper roleTableMapper;
    @Autowired
    private ApiV2Service apiV2Service;
    @Autowired
    private WXBSystemConfig wxbSystemConfig;
    private ExecutorService executorService = Executors.newSingleThreadExecutor();

    @Override
    public JSONResult addTodayBulletin(TodayBulletinTable tb, String baseIDs, String advice) {
        UserTable userTable = (UserTable) HttpContextUtils.getHttpServletRequest().getSession().getAttribute("user");
        Date now = new Date();
        tb.setName("今日快报"+sdf.format(now));
        tb.setCreateTime(now);
        tb.setUpdateTime(now);
        tb.insert();
        for (String baseID :
                baseIDs.split(",")) {
            List<TodayInformationTable> old = todayInformationTableMapper.selectList(new EntityWrapper<TodayInformationTable>().eq("baseID",baseID));
            if (old.size()>0){
                TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
                return renderError("操作被禁止，此信息已加入到快报！");
            }
            TodayInformationTable tit = new TodayInformationTable();
            tit.setTodayBulletinID(tb.getId());
            tit.setBaseID(Integer.valueOf(baseID));
            tit.insert();
            BaseTable bt = new BaseTable();
            bt.setId(Integer.valueOf(baseID));
            bt.setIsEnabled(2);
            bt.updateById();
        }
        //新增审批流程状态1领导审批中
        BulletinApprovalTable bat = new BulletinApprovalTable();
        bat.setTodayBulletinID(tb.getId());
        bat.setUserID(tb.getApprovalUserID());
        bat.setAdvice(advice);
        bat.setStatus(1);
        bat.setCreateTime(now);
        bat.insert();
        logger.info("新增今日快报"+tb.getId()+"由"+userTable.getLinkdoodID()+"-"+userTable.getLinkdoodName()+"新增");
        pushTemplateMessage(tb);
        return renderSuccess();
    }

    @Override
    public JSONResult updateTodayBulletin(Integer id, TodayBulletinTable tb, String baseIDs) {
        UserTable userTable = (UserTable) HttpContextUtils.getHttpServletRequest().getSession().getAttribute("user");
        tb.setId(id);
        tb.updateById();
        todayInformationTableMapper.deleteById(id);
        for (String baseID :
                baseIDs.split(",")) {
            TodayInformationTable tit = new TodayInformationTable();
            tit.setTodayBulletinID(tb.getId());
            tit.setBaseID(Integer.valueOf(baseID));
            tit.insert();
        }
        logger.info("变更今日快报"+tb.getId()+"由"+userTable.getLinkdoodID()+"-"+userTable.getLinkdoodName()+"变更");
        return renderSuccess();
    }

    @Override
    public JSONResult getTodayBulletin(Integer id) {
        TodayBulletinTable tbt = todayBulletinTableMapper.selectById(id);
        UserTable createUser = userTableMapper.selectById(tbt.getCreateUserID());
        tbt.setCreateUserInfo(createUser);
        UserTable approvalUser = userTableMapper.selectById(tbt.getApprovalUserID());
        tbt.setApprovalUserInfo(approvalUser);
        EntityWrapper<BulletinApprovalTable> ew = new EntityWrapper<>();
        ew.eq("todayBulletinID",tbt.getId());
        List<BulletinApprovalTable> bats = bulletinApprovalTableMapper.selectList(ew);
        for (BulletinApprovalTable bat :
                bats) {
            bat.setUserInfo(userTableMapper.selectById(bat.getUserID()));
        }
        tbt.setApprovalList(bats);
        EntityWrapper<TodayInformationTable> ew2 = new EntityWrapper<>();
        ew2.eq("todayBulletinID",tbt.getId());
        List<TodayInformationTable> tits = todayInformationTableMapper.selectList(ew2);
        List<BaseTable> bts = new ArrayList<>();
        for (TodayInformationTable tit :
                tits) {
            BaseTable bt = baseTableMapper.selectById(tit.getBaseID());
            UserTable createUserInfo = userTableMapper.selectById(bt.getCreateUserID());
            bt.setCreateUserInfo(createUserInfo);
            if (bt.getInfoType()==1){
                InformationTable it = informationTableMapper.selectById(tit.getBaseID());
                bt.setExtend(it);
            }else if (bt.getInfoType()==2){
                RiskTable rt = riskTableMapper.selectById(tit.getBaseID());
                List<IndustryTable> industryList = industryTableMapper.selectList(new EntityWrapper<IndustryTable>().in("id",rt.getIndustryIDs().split(",")));
                rt.setIndustryList(industryList);
                List<RegionTable> regionList = regionTableMapper.selectList(new EntityWrapper<RegionTable>().in("id",rt.getRegionIDs().split(",")));
                rt.setRegionList(regionList);
                bt.setExtend(rt);
            }else if (bt.getInfoType()==3){
                EventTable et = eventTableMapper.selectById(tit.getBaseID());
                List<IndustryTable> industryList = industryTableMapper.selectList(new EntityWrapper<IndustryTable>().in("id",et.getIndustryIDs().split(",")));
                et.setIndustryList(industryList);
                List<RegionTable> regionList = regionTableMapper.selectList(new EntityWrapper<RegionTable>().in("id",et.getRegionIDs().split(",")));
                et.setRegionList(regionList);
                bt.setExtend(et);
            }
            bts.add(bt);
        }
        tbt.setInfos(bts);
        return renderSuccess(tbt);
    }

    @Override
    public JSONResult getListTodayBulletin(Page<TodayBulletinTable> page, Integer type, String startTime, String endTime, String title) {
        UserTable userTable = (UserTable) HttpContextUtils.getHttpServletRequest().getSession().getAttribute("user");
        RoleTable roleTable = roleTableMapper.selectById(userTable.getRoleID());
        EntityWrapper<TodayBulletinTable> ew = new EntityWrapper<>();
        if (type==0){
            ew.where("status!=3");
        }else if (type==1){
            ew.eq("status",3);
        }
        if (!roleTable.getRoleType().equals("ROLE_DUTY")){
            ew.and("(createUserID = {0} or approvalUserID = {0} or id in (select todayBulletinID from BULLETIN_APPROVAL_TABLE where userID = {0}))",userTable.getLinkdoodID());
        }
        if (StringUtils.isNotEmpty(title)){
            ew.like("name",title);
        }
        if (StringUtils.isNotEmpty(startTime)&&StringUtils.isNotEmpty(endTime)){
            ew.between("createTime",startTime+" 00:00:00",endTime+" 23:59:59");
        }else if (StringUtils.isNotEmpty(startTime)&&StringUtils.isEmpty(endTime)){
            ew.and("createTime>={0}",startTime);
        }else if (StringUtils.isEmpty(startTime)&&StringUtils.isNotEmpty(endTime)){
            ew.and("createTime<={0}",endTime);
        }
        if (type==0){
            ew.orderBy("approvalUserID != "+userTable.getLinkdoodID()+",createTime",false);
        }else {
            ew.orderBy("createTime",false);
        }
        page.setRecords(todayBulletinTableMapper.selectPage(page,ew));
        List<TodayBulletinTable> tbts = page.getRecords();
        for (TodayBulletinTable tbt :
                tbts) {
            UserTable createUser = userTableMapper.selectById(tbt.getCreateUserID());
            tbt.setCreateUserInfo(createUser);
            UserTable approvalUser = userTableMapper.selectById(tbt.getApprovalUserID());
            tbt.setApprovalUserInfo(approvalUser);
        }
        page.setRecords(tbts);
        return renderSuccess(page);
    }

    private void pushTemplateMessage(TodayBulletinTable tbt) {
        String appid = apiV2Service.getAppID();
        String content = "时间: " + dateFormat.format(new Date()) + "\n标题：" + tbt.getName() + "\n类别: " + "今日快报" + "\n请您及时处理 ";
        TemplateMessage templateMessage = TemplateMessage.createOne(appid, "今日快报", appid, content, wxbSystemConfig.getTodayBulletinDetailUrl() + "&id=" + tbt.getId(),
                tbt.getApprovalUserID());
        try {
            executorService.execute(new DDIORunnable(apiV2Service, "sendTemplateMsg", templateMessage, TemplateMessage.class));
        } catch (NoSuchMethodException e) {
            logger.info("推送今日快报(ID" + tbt.getId() + ")消息失败! ");
            e.printStackTrace();
        }
    }
}
